package cs4280.ass2.persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.log4j.Logger;

import cs4280.ass2.entity.Member;
import cs4280.ass2.entity.User;

public class MemberDao extends BaseDao {
	private static final Logger logger = Logger.getLogger(MemberDao.class);
	private static final String _SELECT_BY_ID = "select * from APP_USER where ID = ? and TYPE = '" + User.USER_TYPE_MEMBER + "'";
	private static final String _SELECT_ALL = "select * from APP_USER where TYPE = '" + User.USER_TYPE_MEMBER + "' order by FIRST_NAME asc";
	private static final String _INSERT_NEW_MEMBER = "INSERT INTO [APP_USER] (CREATE_DATE, CREATE_USER, MODIFY_DATE, MODIFY_USER, FIRST_NAME, LAST_NAME, LOGIN, PASSWORD, TYPE, LOYALTY_POINT, APP_USER_STATUS) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
	private static final String _UPDATE = "";
	private static final String _DELETE_MEMBER = "UPDATE APP_USER SET APP_USER_STATUS = '" + User.APP_USER_DELETED + "' WHERE ID = ?";
	private static final String _CHECK_PASSWORD = "SELECT id FROM APP_USER WHERE id = ? AND password = ?";
	private static final String _CHANGE_PASSWORD = "UPDATE APP_USER SET password = ? WHERE id = ?";
	private static final String _UPDATE_LOYALITY_POINT = "update APP_USER set LOYALTY_POINT = ? ,MODIFY_USER= ? where ID = ? and TYPE = '" + User.USER_TYPE_MEMBER + "'";
	private static MemberDao memberDao = null;

	public static MemberDao getInstance() {
		if (memberDao == null)
			memberDao = new MemberDao();
		return memberDao;
	}

	public Member retrieveMember(long id) {
		Member member = null;
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet result = null;

		try {
			connection = getConnection();
			statement = connection.prepareStatement(_SELECT_BY_ID, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
			statement.setLong(1, id);
			result = statement.executeQuery();
			if (result.next()) {
				member = new Member();
				member.setId(result.getLong("id"));
				member.setFirstName(result.getString("first_name"));
				member.setLastName(result.getString("last_name"));
				member.setLogin(result.getString("login"));
				member.setPassword(result.getString("password"));
				member.setType(result.getString("type"));
				member.setLoyaltyPoint(result.getDouble("loyalty_point"));
				member.setAppUserStatus(result.getString("APP_USER_STATUS"));
				member.setCreateDate(toUtilDate(result.getTimestamp("create_date")));
				member.setCreateUser(result.getLong("create_user"));
				member.setModifyDate(toUtilDate(result.getTimestamp("modify_date")));
				member.setModifyUser(result.getLong("modify_user"));
			}
		} catch (SQLException e) {
			logger.error("Fail to retrieveMember ", e);
		} finally {
			DbUtils.closeQuietly(result);
			DbUtils.closeQuietly(statement);
			DbUtils.closeQuietly(connection);
		}
		return member;
	}

	public List<Member> retrieveAllMember() {
		List<Member> memberList = new ArrayList<Member>();
		Connection connection = null;
		Statement statement = null;
		ResultSet result = null;

		try {
			connection = getConnection();
			statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
			result = statement.executeQuery(_SELECT_ALL);

			Member member;
			while (result.next()) {
				member = this.retrieveMember(result.getLong("id"));
				memberList.add(member);
			}
		} catch (SQLException e) {
			logger.error("Fail to retrieveMember ", e);
		} finally {
			DbUtils.closeQuietly(result);
			DbUtils.closeQuietly(statement);
			DbUtils.closeQuietly(connection);
		}
		return memberList;
	}

	public void registerMember(Member member) {
		Connection connection = null;
		PreparedStatement statement = null;
		try {
			connection = getConnection();
			statement = connection.prepareStatement(_INSERT_NEW_MEMBER, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

			// Context initCtx = new InitialContext();
			// //Context envCtx = (Context)initCtx.lookup("java:comp/env");
			// //DataSource ds = (DataSource)envCtx.lookup("jdbc/cinema");
			// DataSource ds2 = (DataSource)
			// initCtx.lookup("java:comp/env/jdbc/cinema");
			//
			// Connection con = ds2.getConnection();

			statement = connection.prepareStatement(_INSERT_NEW_MEMBER, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

			statement.setTimestamp(1, toSQLDate(member.getCreateDate()));
			statement.setLong(2, member.getCreateUser());
			statement.setTimestamp(3, toSQLDate(member.getModifyDate()));
			statement.setLong(4, member.getModifyUser());
			statement.setString(5, member.getFirstName());
			statement.setString(6, member.getLastName());
			statement.setString(7, member.getLogin());
			statement.setString(8, member.getPassword());
			statement.setString(9, User.USER_TYPE_MEMBER);
			statement.setDouble(10, member.getLoyaltyPoint());
			statement.setString(11, member.getAppUserStatus());

			int rows = statement.executeUpdate();

			// // Added to test JNDI
			// DbUtils.closeQuietly(con);

		} catch (SQLException e) {
			logger.error("Fail to create member ", e);
			// } catch (NamingException e) {
			// logger.error("JNDI resource is not available ", e);
		} finally {
			DbUtils.closeQuietly(statement);
			DbUtils.closeQuietly(connection);

		}
	}

	public void updateMember(Member member) {

	}

	public void deleteMember(long id) {
		Connection connection = null;
		PreparedStatement pstat = null;
		try {
			connection = getConnection();
			pstat = connection.prepareStatement(_DELETE_MEMBER, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

			pstat.setLong(1, id);
			int rows = pstat.executeUpdate();

		} catch (SQLException e) {
			logger.error("Fail to delete member ", e);
		} finally {
			DbUtils.closeQuietly(pstat);
			DbUtils.closeQuietly(connection);
		}
	}

	public boolean matchPassword(long id, String password){
		Connection connection = null;
		PreparedStatement pstat = null;
		boolean isMatch = false;
		try {
			connection = getConnection();
			pstat = connection.prepareStatement(_CHECK_PASSWORD, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

			pstat.setLong(1, id);
			pstat.setString(2, password);
			int rows = pstat.executeUpdate();
			if (rows >0)
				isMatch = true;
		} catch (SQLException e) {
			logger.error("Fail to get user ", e);
		} finally {
			DbUtils.closeQuietly(pstat);
			DbUtils.closeQuietly(connection);
		}
		return isMatch;
	}
	
	public void changePassword(long id, String password){
		Connection connection = null;
		PreparedStatement pstat = null;
		try {
			connection = getConnection();
			pstat = connection.prepareStatement(_CHANGE_PASSWORD, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

			pstat.setLong(1, id);
			pstat.setString(2, password);
			int rows = pstat.executeUpdate();
		} catch (SQLException e) {
			logger.error("Fail to get user ", e);
		} finally {
			DbUtils.closeQuietly(pstat);
			DbUtils.closeQuietly(connection);
		}
	}
	
	public void updateLoyalityPoint(long targetUserId, double newLoyalityPoint,long userId){
		Connection connection = null;
		PreparedStatement pstat = null;
		try {
			connection = getConnection();
			pstat = connection.prepareStatement(_UPDATE_LOYALITY_POINT, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
			pstat.setDouble(1, newLoyalityPoint);
			pstat.setLong(2, userId);
			pstat.setLong(3, targetUserId);
			int rows = pstat.executeUpdate();
		} catch (SQLException e) {
			logger.error("Fail to get user ", e);
		} finally {
			DbUtils.closeQuietly(pstat);
			DbUtils.closeQuietly(connection);
		}
	}
}
